<?php
/*------------------------------------------------------------------
 | Software: APHP - A PHP TOP Framework
 | Site: https://aphp.top
 |------------------------------------------------------------------
 | CopyRight(C)2020-2024 大松栩<24203741@qq.com>,All Rights Reserved.
 |-----------------------------------------------------------------*/
declare(strict_types=1);
namespace middleware;
use Closure;
// 管理员操作日志中件间
class Log
{
    public function run(Closure $next, array $params = []): void
    {
        $next();
        if (site('is_log', 0) == 1) {
            $user = session('user');
            $data = [];
            $data['admin_id'] = $user['id'] ?? '0';
            $data['admin_name'] = $user['username'] ?? '无';
            $data['controller'] = get_controller();
            $data['method'] = get_action();
            $data['title'] = $this->getTitle($data['controller'], $data['method']);
            $data['content'] = $params['sql'] ?? '暂无';
            $data['user_ip'] = get_ip();
            $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $data['create_time'] = time();
            $data['status'] = 1;
            db('admin_log')->noLog()->insert($data);
        }
    }

    protected function getTitle(string $controller, string $method): string
    {
        $controller = name_to_snake($controller);
        $title1 = db('auth')->where('controller', $controller)->value('title');
        if (empty($title1)) {
            $other = ['index' => '首页', 'api' => '接口', 'database' => '数据库', 'login' => '后台', 'profile' => '个人'];
            $title1 = $other[$controller] ?? ucfirst($controller);
        }
        $title2 = db('auth_node')->where('controller', $controller)->where('method', $method)->value('title');
        if (empty($title2)) {
            $action = ['index' => '列表', 'add' => '新增', 'edit' => '修改', 'del' => '删除', 'multi'=>'更新字段', 'work_menu'=>'快捷菜单', 'upload'=>'上传', 'password'=>'改密', 'avatar'=>'换头像', 'login' => '登录'];
            $title2 = $action[$method] ?? $method;
        }
        return $title1.'-'.$title2;
    }

}